#!/bin/bash

# For the license, see the LICENSE file in the root directory.

DIR=$(dirname "$0")
ROOT=${DIR}/..
SWTPM=swtpm
SWTPM_EXE=$ROOT/src/swtpm/$SWTPM
TPMDIR=`mktemp -d`
TPMAUTHORING=$ROOT/src/swtpm_setup/swtpm_setup
PID_FILE=$TPMDIR/${SWTPM}.pid
PATH=${PWD}/${ROOT}/src/swtpm:$PATH
PATH=${PWD}/${ROOT}/src/swtpm_setup:$PATH
PATH=${PWD}/${ROOT}/src/swtpm_bios:$PATH

trap "cleanup" SIGTERM EXIT

function cleanup()
{
	rm -rf $TPMDIR
	if [ -n "$PID" ]; then
		kill -SIGTERM $PID 2>/dev/null
	fi
}

PORT=11234

export TCSD_TCP_DEVICE_HOSTNAME=localhost
export TCSD_TCP_DEVICE_PORT=$PORT
export TCSD_USE_TCP_DEVICE=1

function wait_port_open()
{
	local port=$1
	local pid=$2

	sleep 0.2
	for ((i = 0; i < 20; i++)); do
		if [ -n "$(netstat -naptl 2>/dev/null |
			   grep "LISTEN" |
			   grep " $pid/" |
			   grep ":$port ")" ]; then
			return 0
		fi
		sleep 0.2
	done
	return 1
}

function wait_port_closed()
{
	local port=$1
	local pid=$2

	for ((i = 0; i < 20; i++)); do
		if [ -z "$(netstat -naptl 2>/dev/null |
			   grep "LISTEN" |
			   grep " $pid/" |
			   grep ":$port ")" ]; then
			return 0
		fi
		sleep 0.2
	done
	return 1
}

# Test 1: test port and directory command line parameters

$SWTPM_EXE socket -p $PORT --tpmstate dir=$TPMDIR --pid file=$PID_FILE &>/dev/null &
PID=$!

wait_port_open $PORT $PID

kill -0 $PID
if [ $? -ne 0 ]; then
	echo "Test 1 failed: TPM process not running"
	exit 1
fi

if [ ! -r $PID_FILE ]; then
	echo "Error: CUSE TPM did not write pidfile."
	exit 1
fi

PIDF="$(cat $PID_FILE)"
if [ "$PIDF" != "$PID" ]; then
	echo "Error: CUSE TPM wrote pid $PIDF, but found $PID."
	exit 1
fi


swtpm_bios &>/dev/null

if [ $? -ne 0 ]; then
	echo "Test 1 failed: tpm_bios did not work"
	exit 1
fi

kill -SIGTERM $PID &>/dev/null
sleep 1

exec 20<&1-; exec 21<&2-
kill -0 $PID &>/dev/null
RES=$?
exec 1<&20-; exec 2<&21-

if [ $RES -eq 0 ]; then
	kill -SIGKILL $PID
	echo "Test 1 failed: TPM process did not terminate on SIGTERM"
	exit 1
fi

echo "Test 1 passed"
cleanup

# Test 2: test port, directory and terminate command line parameters (-t)
#         that causes the swtpm process to exit upon connection close
TPMDIR=`mktemp -d`

$SWTPM_EXE socket -p $PORT --tpmstate dir=$TPMDIR -t &>/dev/null &
PID=$!

wait_port_open $PORT $PID

exec 20<&1-; exec 21<&2-
kill -0 $PID
RES=$?
exec 1<&20-; exec 2<&21-

if [ $RES -ne 0 ]; then
	echo "Test 2 failed: TPM process not running"
	exit 1
fi

exec 200<> /dev/tcp/localhost/$PORT
if [ $? -ne 0 ]; then
	echo "Test 2 failed: Could not connect to TPM"
	exit 1
fi

exec 200>&-

wait_port_closed $PORT $PID
# Give it time to fully shut down
sleep 0.2

exec 20<&1-; exec 21<&2-
kill -0 $PID
RES=$?
exec 1<&20-; exec 2<&21-

if [ $RES -eq 0 ]; then
	kill -SIGKILL $PID
	echo "Test 2 failed: TPM process did not terminate on connection loss"
	exit 1
fi

echo "Test 2 passed"

exit 0
